const initialState = {
  cartList:JSON.parse(localStorage.getItem("cart"))||[],
  totalCount:0,
  allSelect:false,
  totalAll:0
};

 export function cartReducer(state=initialState,action){
   switch(action.type){
     case "ADDCART":
       //去重商品
       var flag = false;
       state.cartList.forEach((el)=>{
         if(el._id===action.item._id){
           flag = true;
           el.count+=1;
         }
       })

       if(!flag){
         action.item.count = 1;
         action.item.checked = false;
         state.cartList.push(action.item)
       }

       localStorage.setItem("cart",JSON.stringify(state.cartList));
       return {
        cartList:state.cartList,
        totalCount:state.totalCount,
        totalAll:state.totalAll,
        allSelect:state.allSelect
       };
     case "CHANGEITEMSTATUS":
       //找到要修改状态的商品
       state.cartList.forEach((element)=>{
         if(element._id===action.item._id){
           element.checked = action.item.checked;
         }
       })

       //同步全选状态
       var result = state.cartList.every((element)=>{
          return element.checked === true;
       })
       state.allSelect = result;


       //总价 总量
       state.totalCount = 0;
       state.cartList.forEach((element)=>{
         if(element.checked){
          state.totalCount+=element.count
         }
       })

       state.totalAll = 0;
       state.cartList.forEach((element)=>{
        if(element.checked){
         state.totalAll+=element.salePrice*state.totalCount
        }
      })

       return {
        cartList:state.cartList,
        totalCount:state.totalCount,
        totalAll:state.totalAll,
        allSelect:state.allSelect
       }
     case "ALLSELECT":
       state.allSelect = action.boolean;
       //每个商品选中状态
       state.cartList.forEach((element)=>{
          element.checked = action.boolean;
       })

       //总价 总量
       state.totalCount = 0;
       state.cartList.forEach((element)=>{
         if(element.checked){
          state.totalCount+=element.count
         }
       })

       state.totalAll = 0;
       state.cartList.forEach((element)=>{
        if(element.checked){
          console.log(element.salePrice)
         state.totalAll+=element.salePrice*state.totalCount
        }
      })

       return {
         cartList:state.cartList,
         totalCount:state.totalCount,
         totalAll:state.totalAll,
         allSelect:state.allSelect
       };
     default:
       return state;
   }
}